<!--
 * @Author: 梁青春
 * @Date: 2022-04-26 14:27:50
 * @LastEditTime: 2022-04-28 16:05:31
 * @LastEditors: 梁青春
-->
<template>
  <el-dropdown>
    <span class="dropdown-link">主题</span>
    <el-dropdown-menu slot="dropdown">
        <el-color-picker v-model="theme" :predefine="['#1B6CD8', '#1890ff', '#304156','#11a983', '#13c2c2', '#6959CD']"></el-color-picker>
    </el-dropdown-menu>
  </el-dropdown>
</template>
<script>
const version = require('element-ui/package.json').version // 从node_modules中获取element-ui 版本号
const ORIGINAL_THEME = '#1B6CD8' // 默认主题色

export default {
  data() {
    return {
      chalk: '', // content of theme-chalk css
      theme: ''
    }
  },
  
  mounted() {
    if(localStorage.getItem('colorPicker')){
      this.theme = localStorage.getItem('colorPicker')
    } else {
      this.theme = ORIGINAL_THEME
    }
  },
  
  watch: {
   //  监听主题变更并编译主题
    async theme(val) {
      const oldVal = this.chalk ? this.theme : ORIGINAL_THEME

      if (typeof val !== 'string') return      
        
        for (let i = 10; i >= 0; i--) {
          const o = Number((i / 10).toFixed(2))
          switch (o) {
            case 0.9:
              document
              .getElementsByTagName("body")[0]
              .style.setProperty("--color-primary-09", val+'E6');
              break;
            case 0.8:
              document
              .getElementsByTagName("body")[0]
              .style.setProperty("--color-primary-08", val+'CC');
              break;
            case 0.7:
              document
              .getElementsByTagName("body")[0]
              .style.setProperty("--color-primary-07", val+'B3');
              break;
            case 0.6:
              document
              .getElementsByTagName("body")[0]
              .style.setProperty("--color-primary-06", val+'99');
              break;
            case 0.5:
              document
              .getElementsByTagName("body")[0]
              .style.setProperty("--color-primary-05", val+'80');
              break;
            case 0.4:
              document
              .getElementsByTagName("body")[0]
              .style.setProperty("--color-primary-04", val+'66');
              break;
            case 0.3:
              document
              .getElementsByTagName("body")[0]
              .style.setProperty("--color-primary-03", val+'4D');
              break;
            case 0.2:
              document
              .getElementsByTagName("body")[0]
              .style.setProperty("--color-primary-02", val+'33');
              break;
            case 0.1:
              document
              .getElementsByTagName("body")[0]
              .style.setProperty("--color-primary-01", val+'1A');
              break;
            case 0.0:
              document
              .getElementsByTagName("body")[0]
              .style.setProperty("--color-primary-00", val+'00');
              break;
            default:
              document
              .getElementsByTagName("body")[0]
              .style.setProperty("--color-primary", val);
              break;
          }
        }
      localStorage.setItem('colorPicker',val)
      //  获取新老主题色的色值集合
      const themeCluster = this.getThemeCluster(val.replace('#', ''))
      const originalCluster = this.getThemeCluster(oldVal.replace('#', ''))
      const $message = this.$message({
        message: '正在编译主题',
        type: 'success',
        duration: 0,
        iconClass: 'el-icon-loading'
      })
      // 将style渲染到DOM中
      const getHandler = (variable, id) => {
        return () => {
          const originalCluster = this.getThemeCluster(ORIGINAL_THEME.replace('#', ''))
          const newStyle = this.updateStyle(this[variable], originalCluster, themeCluster)
          let styleTag = document.getElementById(id)
          if (!styleTag) {
            styleTag = document.createElement('style')
            styleTag.setAttribute('id', id)
            document.head.appendChild(styleTag)
          }
          styleTag.innerText = newStyle
        }
      }
      //  初次进入或刷新时动态加载CSS文件
      if (!this.chalk) {
        const url = `https://unpkg.com/element-ui@${version}/lib/theme-chalk/index.css`
        await this.getCSSString(url, 'chalk')
      }
      const chalkHandler = getHandler('chalk', 'chalk-style')
      chalkHandler()
      
      const styles = [].slice.call(document.querySelectorAll('style')).filter(style => {
          const text = style.innerText
          return new RegExp(oldVal, 'i').test(text) && !/Chalk Variables/.test(text)
      })
      styles.forEach(style => {
        const { innerText } = style
        if (typeof innerText !== 'string') return
        style.innerText = this.updateStyle(innerText, originalCluster, themeCluster)
      })
      
      $message.close()
    }
  },
 
   methods: {
   //  更新主题色
    updateStyle(style, oldCluster, newCluster) {
      let newStyle = style
      oldCluster.forEach((color, index) => {
        newStyle = newStyle.replace(new RegExp(color, 'ig'), newCluster[index])
      })
      return newStyle
    },
    // 获取样式文件内容
    getCSSString(url, variable) {
      return new Promise(resolve => {
        const xhr = new XMLHttpRequest()
        xhr.onreadystatechange = () => {
          if (xhr.readyState === 4 && xhr.status === 200) {
            this[variable] = xhr.responseText.replace(/@font-face{[^}]+}/g, '') // 去掉字体样式
            .replace(/.el-icon-[a-zA-Z0-9-:^]+before{content:"[^}]+}/g, '') // 去掉图标样式
            resolve()
          }
        }
        xhr.open('GET', url)
        xhr.send()
      })
    },
    // 获取主题同类色的集合
    getThemeCluster(theme) {
      const tintColor = (color, tint) => {
        let red = parseInt(color.slice(0, 2), 16)
        let green = parseInt(color.slice(2, 4), 16)
        let blue = parseInt(color.slice(4, 6), 16)
        if (tint === 0) { // when primary color is in its rgb space
          return [red, green, blue].join(',')
        } else {
          red += Math.round(tint * (255 - red))
          green += Math.round(tint * (255 - green))
          blue += Math.round(tint * (255 - blue))
          red = red.toString(16)
          green = green.toString(16)
          blue = blue.toString(16)
          return `#${red}${green}${blue}`
        }
      }
      const shadeColor = (color, shade) => {
        let red = parseInt(color.slice(0, 2), 16)
        let green = parseInt(color.slice(2, 4), 16)
        let blue = parseInt(color.slice(4, 6), 16)
        red = Math.round((1 - shade) * red)
        green = Math.round((1 - shade) * green)
        blue = Math.round((1 - shade) * blue)
        red = red.toString(16)
        green = green.toString(16)
        blue = blue.toString(16)
        return `#${red}${green}${blue}`
      }
      const clusters = [theme]
      for (let i = 0; i <= 9; i++) {
        // console.log(Number((i / 10).toFixed(2)))
        clusters.push(tintColor(theme, Number((i / 10).toFixed(2))))
      }
      clusters.push(shadeColor(theme, 0.1))
      return clusters
    }
   }
}
</script>
<style>
.dropdown-link {
  color: #fff;
  width: 20px;
}
</style>